/**
 * 基本信息
 *
 * @format
 */

import { BaseDao, TBAPIS } from '../../sdk'
import { SIGN_DB_NAME } from '../../db'
import { ACTIVITY_STATUS } from '../../constants'
import UserService from './user.service'
import { getToday } from '../../utils'
import { CODE_TYPES } from '../../errorCode'
import { getDistanceDays } from '../../utils/common/sign'
import { formatDate } from '../../utils/common/date'

export default class SignService extends UserService {
  context: IContext<any>
  signdao: IBaseDao
  constructor(context: IContext<any>) {
    super(context)
    this.signdao = new BaseDao(context, SIGN_DB_NAME)
  }

  async doSign(userInfo: IUserInfo, activityId: string, subscribeSignDay = '') {
    const { openId } = this.context
    const { userNick } = userInfo
    const today = getToday()
    const signResult = await this.signdao.insertOne<IUserSign>({
      activityId,
      openId,
      userNick,
      isSignLater: !!subscribeSignDay,
      createDay: today,
      signTime: subscribeSignDay ? formatDate(subscribeSignDay).getDate() : formatDate().getDate(),
      signDay: subscribeSignDay || today,
      createTime: Date.now()
    })

    if (!signResult) return CODE_TYPES.SYSTEM_ERROR

    return {
      signId: signResult
    }
  }

  async getSignList(activityId: string) {
    const { openId } = this.context
    const signInfoList: ISignInfoAggregate[] = await this.signdao.aggregate(
      { $match: { activityId, openId } },
      {
        $project: {
          d: { $dayOfYear: '$signTime' },
          y: { $year: '$signTime' },
          signTime: '$signTime',
          signDay: '$signDay'
        }
      }
    )

    return signInfoList
  }
}
